package com.lei.study.lock;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.RetryNTimes;

import java.util.concurrent.CountDownLatch;

/**
 * 并发测试
 * 使用
 *
 * @author 伍磊
 */
public class ConcurrencyTest implements Runnable{

    public static int stock = 3;

    public static CountDownLatch countDownLatch = new CountDownLatch(10);

    public static CuratorFramework CURATOR_FRAMEWORK;

    public static InterProcessMutex MUTEX;

    public static void main(String[] args) {
        CURATOR_FRAMEWORK = CuratorFrameworkFactory.newClient("localhost:2181,localhost:2182,localhost:2183,localhost:2184", new RetryNTimes(3, 1000));
        CURATOR_FRAMEWORK.start();
        MUTEX = new InterProcessMutex(CURATOR_FRAMEWORK, "/Mutex");
        for (int i = 0; i < 10; i++) {
            new Thread(new ConcurrencyTest()).start();
            countDownLatch.countDown();
        }
    }

    @Override
    public void run() {
        try {
            countDownLatch.await();
            // 获取互斥锁
            MUTEX.acquire();
            if (stock > 0) {
                System.out.println(Thread.currentThread().getName() + " 抢到了，剩余库存: " + --stock);
            }
            MUTEX.release();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
